/**
 * @Title: BroadcastHeaderService.java
 * @Description: 广播消息
 * @author 7828wc
 * @date 2015年7月28日 上午10:37:00
 */
package com.shanghaionstar.sqlite;

import android.content.Context;

import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.sqlite.entities.BroadcastHeaderEntity;
import com.onstar.cn.sqlite.xutil.db.sqlite.Selector;
import com.onstar.cn.sqlite.xutil.db.sqlite.WhereBuilder;
import com.onstar.cn.sqlite.xutil.exception.DbException;

import java.util.List;

/**
 * @ClassName: BroadcastHeaderService
 * @Description: 广播消息
 * @author 7828wc
 * @date 2015年7月28日 上午10:37:00
 */
public class BroadcastHeaderService extends BaseSqlImp {
    public static final String DEFAULTVIN = "123";

    public BroadcastHeaderService(Context context) {
        super(context);
    }

    public String getLastBroadcastID(String vin) {
//		List<BroadcastHeaderEntity> list = getAll(null, "vin = ?", new String[]{vin}, null, null, "broadcastId desc", "1");
        List<BroadcastHeaderEntity> list = null;
        try {
            list = mDbUtils.findAll(Selector.from(BroadcastHeaderEntity.class)
                    .where("vin", "=", vin).orderBy("broadcastId", true).limit(1));
        } catch (DbException e) {
            e.printStackTrace();
        }
        if (list != null && list.size() > 0) {
            return list.get(0).getBroadcastId();
        }
        return null;
    }

    /**
     *
     * @Title: getAllBroadcastHeader
     * @Description:查询所有未读或已读消息isRead='true' or isRead='false'
     * @param @return    设定文件
     * @return List<BroadcastHeaderEntity>    返回类型
     * @throws
     */
    public List<BroadcastHeaderEntity> getAllBroadcastHeader(String vin, String isRead) {
//		 List<BroadcastHeaderEntity> list = getAll(null, "vin = ? and isRead = ?", new String[]{vin,isRead}, null, null,null, null);
        List<BroadcastHeaderEntity> list = null;
        try {
            list = mDbUtils.findAll(Selector.from(BroadcastHeaderEntity.class).where("vin", "=", vin).and("isRead", "=", isRead));
        } catch (DbException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * @Title: insert
     * @Description: Insert data list to table
     * @param @param headers
     * @param @param vin
     * @param @return 设定文件
     * @return long 返回类型
     * @throws
     */
    public long insert(List<BroadcastHeaderEntity> headers, String vin) {
        if (CommonUtil.isNull(vin)) {
            vin = DEFAULTVIN;
        }
        long id = -1;
        deleteExpireFile(headers, vin);
        for (BroadcastHeaderEntity entity : headers) {
            // super.insertOrUpdate(entity, "", selectionArgs);
            entity.setVin(vin);
            try {
                BroadcastHeaderEntity headerEntity = mDbUtils.findFirst(Selector.from(BroadcastHeaderEntity.class).where("broadcastId", "=", entity.getBroadcastId()));
                if (headerEntity != null) {
                    entity.setIsRead(headerEntity.getIsRead());
                    mDbUtils.update(entity, WhereBuilder.b("broadcastId", "=", entity.getBroadcastId()));
                } else {
                    mDbUtils.saveBindingId(entity);
                }
            } catch (DbException e) {
                e.printStackTrace();
            }
//			mDbUtils.saveBindingId(entity)
//			if (checkDataIfExits(entity, vin)) {
//				id = super.update(entity, "broadcastId=?", new String[] { entity.getBroadcastId() });
//			} else {
//				id = super.insert(entity);
//			}
        }
        try {
            id = mDbUtils.count(BroadcastHeaderEntity.class);
        } catch (DbException e) {
            e.printStackTrace();
        }
        return id;
    }

    /**
     * @Title: update
     * @Description: Update data to table
     * @param @param p_info
     * @param @param vin
     * @param @return 设定文件
     * @return long 返回类型
     * @throws
     */
    public void update(BroadcastHeaderEntity entity) {
        if (entity.getIsRead().equals("false")) {
            return;
        }
        try {
            mDbUtils.update(entity,WhereBuilder.b("broadcastId","=",entity.getBroadcastId()));
//            mDbUtils.saveBindingId(entity);
        } catch (DbException e) {
            e.printStackTrace();
        }
//		return super.update(entity);
    }

    /**
     * @Title: delete
     * @Description: Delete data by broadcastId
     * @param @param id 设定文件
     * @return void 返回类型
     * @throws
     */
    public void delete(String id) {
//		super.delete("ID=? and language=?", new String[] { id, DeviceUtil.getLanguage() });
        try {
            mDbUtils.delete(BroadcastHeaderEntity.class, WhereBuilder.b("ID", "=", id).and("language", "=", DeviceUtil.getLanguage()));
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Title: deleteExpireFile
     * @Description: Delete expire data
     * @param @param headers
     * @param @param vin 设定文件
     * @return void 返回类型
     * @throws
     */
    public void deleteExpireFile(List<BroadcastHeaderEntity> headers, String vin) {
        if (CommonUtil.isNull(vin)) {
            vin = DEFAULTVIN;
        }
        if (headers.size() == 0) {
//			delete("vin=?", new String[] { vin });
            try {
                mDbUtils.delete(BroadcastHeaderEntity.class, WhereBuilder.b("vin", "=", vin));
            } catch (DbException e) {
                e.printStackTrace();
            }
            return;
        }

        try {
//            String[] strValue = new String[headers.size() + 2];
//            String strWhere = " 1=1 ";
//            if (headers.size() > 0) {
//                strWhere += "and (";
//                for (int i = 0; i < headers.size(); i++) {
//                    if (headers.size() - 1 == i) {
//                        strWhere += "broadcastId<>?)";
//                    } else {
//                        strWhere += "broadcastId<>? and ";
//                    }
//                    strValue[i] = headers.get(i).getBroadcastId();
//                }
//                strValue[headers.size()] = vin;
//                strValue[headers.size() + 1] = DEFAULTVIN;
//            } else {
//                strValue[0] = vin;
//                strValue[1] = DEFAULTVIN;
//            }

//			LogManager.getInstance().d( "sqlite:sql" + sql + "--strValue:" + strValue);
//			List<BroadcastHeaderEntity> list = super.rawQuery(sql, strValue);
//
//			if (list != null && list.size() > 0) {
//				for (int i = 0; i < list.size(); i++) {
//					// delete(list.get(i).getId() + "");
//					delete("(vin=? or vin=?) and broadcastId=?", new String[]{vin, DEFAULTVIN, list.get(i).getBroadcastId()});
//				}
//			}
            StringBuilder stringBuilder = new StringBuilder("(");
            if (headers != null && headers.size() > 0) {
                for(BroadcastHeaderEntity entity : headers) {
                    stringBuilder.append("\'"+entity.getBroadcastId()+"\'"+",");
                }
            }
            stringBuilder.append("\'-1\')");
//            (vin=" + vin + " or vin=" + DEFAULTVIN + ")
            String sql = "delete from t_onstar_broadcast where broadcastId NOT IN " + stringBuilder.toString() + " and vin IN ("+"\'"+vin+"\'"+","+"\'"+DEFAULTVIN+"\'"+")";
            if(mDbUtils.count(BroadcastHeaderEntity.class)>0)
                mDbUtils.execNonQuery(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Title: checkDataIfExits
     * @Description: The table if exits this data
     * @param @param info
     * @param @param vin
     * @param @return 设定文件
     * @return boolean 返回类型
     * @throws
     */
//    public boolean checkDataIfExits(BroadcastHeaderEntity info, String vin) {
//        try {
////			String sql = "select * from t_onstar_broadcast where broadcastId=?";
////			return super.isExist(sql, new String[] { info.getBroadcastId() });
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return false;
//    }


}
